package cn.tedu.crm.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.tedu.crm.base.exception.ServiceException;
import cn.tedu.crm.user.mapper.PersonalMapper;
import cn.tedu.crm.user.pojo.dto.PasswordUpdateDTO;
import cn.tedu.crm.user.pojo.dto.PersonalUserParam;
import cn.tedu.crm.user.pojo.entity.User;
import cn.tedu.crm.user.pojo.vo.UserVO;
import cn.tedu.crm.user.service.PersonalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class PersonalServiceImpl implements PersonalService {
    @Autowired
    private PersonalMapper personalMapper;
    @Value("${app.upload.url-prefix}")
    private String urlPrefix;

    @Value("${app.upload.path}")
    private String uploadPath;

    @Override
    public UserVO userSelectById() {
        Long userId = StpUtil.getLoginIdAsLong();
        UserVO userVO = new UserVO();
        User user = personalMapper.selectById(userId);
        BeanUtils.copyProperties(user,userVO);
        userVO.setId(userId);
        return userVO;
    }

    @Override
    public void updatePassword(PasswordUpdateDTO dto) {
        // 1. 校验确认密码
        if (!dto.getNewPassword().equals(dto.getConfirmPassword())) {
            throw new ServiceException("两次输入的密码不一致");
        }

        // 2. 获取当前用户
        Long userId = StpUtil.getLoginIdAsLong();
        User user = personalMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 3. 校验原密码
        if (!Objects.equals(dto.getRawPassword(), user.getPassword())) {
            throw new ServiceException("原密码错误");
        }

        // 4. 校验新旧密码是否相同
        if (Objects.equals(dto.getNewPassword(), user.getPassword())) {
            throw new ServiceException("新密码不能与原密码相同");
        }

        // 5. 更新密码
        user.setPassword(dto.getConfirmPassword());
        personalMapper.updateById(user);

        // 6. 强制登出
        StpUtil.logout(userId);
    }

    @Override
    public void updateUser(PersonalUserParam personalUserParam) {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = personalMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException("请重新登录");
        }else {
            BeanUtils.copyProperties(personalUserParam,user);
            personalMapper.updateById(user);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAvatar(String avatar) {
        log.debug("图片路径业务层{}"+avatar);
        Long userId = StpUtil.getLoginIdAsLong();
        User user = personalMapper.selectById(userId);

        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 保留旧头像路径
        String oldAvatar = user.getAvatar();

        // 设置新头像URL
        user.setAvatar(avatar);  // 确保此处接收的是完整URL

        int rows = personalMapper.updateById(user);
        if (rows == 0) {
            throw new ServiceException("头像更新失败");
        }

        // 清理旧头像
        if (StringUtils.hasText(oldAvatar)) {
            cleanOldAvatar(oldAvatar);
        }
    }

    private void cleanOldAvatar(String avatar) {
        try {
            // 转换URL为本地路径
            String relativePath = avatar.replace(urlPrefix, "");
            File oldFile = new File(uploadPath + relativePath);

            if (oldFile.exists()) {
                if (oldFile.delete()) {
                    log.info("旧头像清理成功: {}", avatar);
                } else {
                    log.warn("旧头像清理失败: {}", avatar);
                }
            }
        } catch (Exception e) {
            log.error("旧头像清理异常: {}", e.getMessage());
        }
    }
}
